package com.cd.music.utils;

import java.io.UnsupportedEncodingException;
import java.util.Random;

/**
 * @author yxl  余秀良
 * @description: 加密工具类
 * @date 16-9-2 下午1:42
 * @address: 四川成都
 */
public final class EncryptUtil {
    /**
     * 公共密匙
     */
    private final static String SECRET_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";

    /**
     * 加密
     *
     * @param pwd 要加密的字符串
     * @return 加密后的字符串
     */
    public static String encryption(String pwd) {
        if (StringUtil.isEmpty(pwd) || pwd.length() == 0) {
            return null;
        }
        byte[] buffer = new byte[0];
        try {
            buffer = pwd.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte j, k, m;
        int i = buffer.length, n;
        char[] chars = new char[2 * i];
        Random rnd = new Random();
        for (i = 0; i < buffer.length; i++) {
            n = rnd.nextInt(3) % (4);
            j = (byte) (3 * n + 1);
            buffer[i] = (byte) ((buffer[i] & 0xff) ^ j);
            k = (byte) ((buffer[i] & 0xff) % SECRET_KEY.length());
            m = (byte) ((buffer[i] & 0xff) / SECRET_KEY.length());
            m = (byte) (m * (8) + j);
            chars[2 * i] = SECRET_KEY.charAt((int) k);
            chars[2 * i + 1] = SECRET_KEY.charAt((int) m);
        }
        return String.valueOf(chars);
    }

    /**
     * 解密
     *
     * @param pwd 要解密的字符串
     * @return 解密后字符串
     */
    public static String decryption(String pwd) {
        if (StringUtil.isEmpty(pwd) || pwd.length() == 0) {
            return null;
        }
        int i, n = 0, number = 2;
        byte j, k, m;
        char t1, t2;
        byte[] buffer = new byte[pwd.length() / 2];
        for (i = 0; i < pwd.length(); i += number) {
            t1 = pwd.charAt(i);
            t2 = pwd.charAt(i + 1);
            k = (byte) (SECRET_KEY.indexOf(t1));
            m = (byte) (SECRET_KEY.indexOf(t2));
            j = (byte) ((int) m / 8);
            m = (byte) ((int) m - (int) j * (8));
            buffer[n] = (byte) ((int) j * SECRET_KEY.length() + (int) k);
            buffer[n] ^= m;
            n++;
        }
        try {
            return new String(buffer, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
        //return new String(buffer);
    }

    private EncryptUtil() {
        throw new UnsupportedOperationException("这是一个工具类不能实例化");
    }
}
